/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package  com.edi.runtime.component
{
	import com.edi.proxy.component.*;
	import com.edi.runtime.Event.EDIDataEvent;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.containers.*;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.core.Container;
	import mx.core.UIComponent;
	import mx.events.FlexEvent;
	import mx.managers.PopUpManager;
	import mx.modules.Module;
	import mx.utils.UIDUtil;
	import mx.core.IFlexDisplayObject;
	/**
	 * 
	 * 
	 */	
	public class EDIBasicDataModule extends Module
	{
		private var _appName:String;

		private var _appId:String;

		public var ds:EDIDataSource;
		public var caption:String;

		private var op:String;
		private var toolBar:HBox;
		private var saveBtn:Button;
		private var exitBtn:Button;
		private var itemID:String;
		
		private var eql:String;
		private var proxy:HttpProxy;
		private var gridDesXml:XML;
		private var eqlHead:String="";
		private var paramsObj:Object=new Object();
		private var newTable:EDIDataTable;
		private var datasource:EDIDataSource;
		public var allComponents:ArrayCollection=new ArrayCollection();
		public var uuid:String;
		/**
		 * 构造函数，创建可视化组件
		 * 
		 */		
		public function EDIBasicDataModule()
		{
			super();
			//Alert.show("EDIBasicDataModule load!");
			toolBar=new HBox();
			toolBar.x=0;
			toolBar.y=0;

			toolBar.percentWidth=100;
			toolBar.height=30;
			this.addChild(toolBar);
			
			saveBtn=new Button();
			saveBtn.height=25;
			saveBtn.width=55;
			saveBtn.label="保存"
			toolBar.addChild(saveBtn);
			saveBtn.addEventListener(MouseEvent.CLICK,saveBtnClickHandler);
			
			exitBtn=new Button();
			exitBtn.height=25;
			exitBtn.width=55;
			exitBtn.label="退出"
			toolBar.addChild(exitBtn);
			exitBtn.addEventListener(MouseEvent.CLICK,exitBtnClickHandler);	
			
			ds=new EDIDataSource(this);
			addEventListener(EDIDataEvent.Data_RollingBefore,dataRollingHandler);
			
			//this.addEventListener(Event.ADDED_TO_STAGE,addedHandler);
			this.addEventListener(FlexEvent.CREATION_COMPLETE,onCreateHandler);
		}
		
		private function onCreateHandler(event:Event):void
		{
			var s:String=root.loaderInfo.url;
			
			s=s.substring(s.indexOf("?")+1,s.length);
			//Alert.show(s);
			var params:Array = s.split("&");
			
			for(var i:int=0;i<params.length;i++)
			{
				paramsObj[params[i].toString().split("=")[0]]=params[i].toString().split("=")[1];
			}
			if(paramsObj["app"])
			{
				this._appName=paramsObj["app"].toString();
				proxy=new HttpProxy(this.appName,true,this.ds);
			}
			if(paramsObj["itemID"])
			{
				itemID=paramsObj["itemID"].toString();
				if(paramsObj["op"])
				{
					op=paramsObj["op"].toString();
				}
				if(op=="new")
				{
					datasource = new EDIDataSource(this,null,this.appName);
					newTable = new EDIDataTable(null,datasource);
					newTable.dataSourceName=itemID;
					//如果新增基础资料
				}

				//如果修改基础资料，向服务器要基础资料
/*
				eql="select * from edi_tbdescribe where tableName='"+paramsObj["itemID"].toString()+"'";
				//Alert.show(eql);
				var desPara:EPOParam=new EPOParam();
				//"app1"需要被this.appName代替
				desPara.EQL =eql;
				//TODO下面这句需要重写
				desPara.dsName = "tb_gridDesc";
				proxy.addPoParam(desPara);
				proxy.send();
				proxy.resultCallback=getEqlDataHandeler;
*/
				getChildrenComponent(this);
				buildAndSendEql();
			}
		}

		private function getChildrenComponent(obj:Object):void
		{
			var arr:Array;
			var i:int;
			var o:DisplayObject;
			var t:UIComponent;
			//如果是容器
			if(obj is Container)
			{
				//如果是容器而且是IEDIComponent
				if(obj is IEDIComponent)
				{
					allComponents.addItem(obj);
				}
				else
				{
					arr=Container(obj).getChildren();
					for(i=0;i<arr.length;i++)
					{
						getChildrenComponent(arr[i]);
					}
				}
			}
			else
			{
				if(obj is IEDIComponent)
					allComponents.addItem(obj);
			}
		}
		
		private function getEqlDataHandeler(event:HttpProxyResult):void
		{
			var i:int;
			var rowXml:XML;
			var fieldsStr:String="";
			var field:String="";
			var tempStr:String="";
			var sourcetable:String="";
			var resultXml:XML;
			while(event.poNext())
			{
//				Alert.show(event.currentPoResult.dataSource);
//				
//				if(event.currentPoResult.dsName=="tb_grid")
//				{
//					resultXml=event.currentPoResult.dataSource;
//					for (i=0;i<XMLList(gridDesXml..row).length();i++)
//					{
//						rowXml=XMLList(resultXml..row)[i];
//						rowXml.appendChild(new XML(<selected>false</selected>));
//					}
//				}
				this.ds.addDataTable(event.currentPoResult.dataSource);
				if(event.currentPoResult.dsName==itemID)
				{
					//Alert.show(itemID);
					this.ds.getDataTable(itemID).cursorIndex=0
				}
				
				if(event.currentPoResult.dsName=="tb_gridDesc")
				{
					gridDesXml=event.currentPoResult.dataSource;
					if(paramsObj["op"]=="modify")
					{					
						for (i=0;i<XMLList(gridDesXml..row).length();i++)
						{
							rowXml=XMLList(gridDesXml..row)[i];
							
							if(rowXml.fieldtype=='uniqueidentifier')
							{
								if(this[rowXml.componentid] is EDITextInput)
								{
									EDITextInput(this[rowXml.componentid]).text=UIDUtil.createUID();
									EDITextInput(this[rowXml.componentid]).editable=false;
									EDITextInput(this[rowXml.componentid]).enabled=false;
								}
							}
							
//							sourcetable=rowXml.sourcetable;
//							if(sourcetable!=null && sourcetable!="")
//							{
//								field=rowXml.displayfield;
//								tempStr=sourcetable+"."+field;
//							}
//							else
//							{
								field=rowXml.field;
								tempStr=itemID+"."+field;
//							}
							if(i==0)
							{ 				
								fieldsStr=tempStr;
							}
							else
								fieldsStr=fieldsStr+","+tempStr+" " ;
							
//							Alert.show("sourcetable:"+sourcetable);
//							if(	sourcetable!=null && sourcetable!="")
//							{
//								tempStr=itemID+"."+rowXml.field+"="+sourcetable+"."+rowXml.savefield;
//								eqlHead=eqlHead + " inner join "+ sourcetable +" on " +tempStr;
//							}
						}
						eqlHead="select "+fieldsStr+ " from "+itemID+" "+eqlHead;
						eql=eqlHead+" where "+itemID+"."+paramsObj["key"]+"='"+paramsObj["value"]+"'";
						//Alert.show(eql); 
						var desPara:EPOParam=new EPOParam();
						//"app1"需要被this.appName代替
						desPara.EQL =eql;
						//TODO下面这句需要重写
						desPara.dsName = itemID;//"tb_grid";
						proxy.addPoParam(desPara);
						proxy.send();
						proxy.resultCallback=getEqlDataHandeler;
					}
					else if (paramsObj["op"]=="new")
					{
						for (i=0;i<XMLList(gridDesXml..row).length();i++)
						{
							rowXml=XMLList(gridDesXml..row)[i];
							if(rowXml.fieldtype=='uniqueidentifier')
							{
								if(this[rowXml.componentid] is EDITextInput)
								{
									EDITextInput(this[rowXml.componentid]).text=UIDUtil.createUID();
									EDITextInput(this[rowXml.componentid]).editable=false;
									EDITextInput(this[rowXml.componentid]).enabled=false;
								}
							}
							field=rowXml.field;
							newTable.addField(field,rowXml.fieldtype);
						}
					}
				}
			}
		} 
		private function buildAndSendEql():void
		{
			var i:int;
			var fieldsStr:String="";
			var field:String="";
			var tempStr:String="";
			var sourcetable:String="";
			var ediComp:IEDIComponent;
			if(paramsObj["op"]=="modify")
			{					
				for( i=0;i<allComponents.length;i++)
				{
					ediComp=IEDIComponent(allComponents.getItemAt(i));
					field=ediComp.field;
					//Alert.show(i.toString()+":"+field);
					
					tempStr=itemID+"."+field;
					if(i==0)
					{ 				
						fieldsStr=tempStr;
					}
					else
						fieldsStr=fieldsStr+","+tempStr+" " ;
				}
				eqlHead="select "+fieldsStr+ " from "+itemID+" "+eqlHead;
				eql=eqlHead+" where "+itemID+"."+paramsObj["key"]+"='"+paramsObj["value"]+"'";
				//Alert.show('buildAndSendEql:'+eql); 
				var desPara:EPOParam=new EPOParam();
				//"app1"需要被this.appName代替
				desPara.EQL =eql;
				//TODO下面这句需要重写
				desPara.dsName = itemID;//"tb_grid";
				proxy.addPoParam(desPara);
				proxy.send();
				proxy.resultCallback=getEqlDataHandeler;
			}
			else if (paramsObj["op"]=="new")
			{
				for each(ediComp in allComponents)
				{
					field=ediComp.field;
					newTable.addField(field,ediComp.fieldType);
				}
			}
			
			
		}
		/**
		 * 设置appName
		 * @param value
		 * 
		 */		
		public function set appName(value:String):void{
			_appName=value;
			ds.appName=value;
		}
		public function get appName():String{return _appName==null?"":_appName;}
		
		/**
		 * 设置appId
		 * @param value
		 * 
		 */		
		public function set appId(value:String):void{
			_appId = value;
		}
		
		public function get appId():String{
			return _appId==null?"":_appId;
		}

		/**
		 * 
		 * @param value
		 * 
		 */		
		public function set dsCommit(value:Boolean):void{
			ds.autoCommit=value;
		}
		public function get dsCommit():Boolean{return ds.autoCommit;}
		
		
		private function dataRollingHandler(event:EDIDataEvent):void
		{
			ds.getDataTable(event.tableName).cursorIndex=event.index;
		}
		private function saveBtnClickHandler(event:MouseEvent):void
		{
			var rowXml:XML;
			var i:int;
			//Alert.show(op);
			if(op=="modify")
			{
				//更新记录
				ds.appName=this.appName;
				ds.getDataTable(itemID).commitToServer();
				EDIAlert.show("已提交服务器");
			}
			else if (op=="new")
			{
				//新增记录
				var row:EDIDataRow=newTable.newRow();
				//Alert.show(gridDesXml.toXMLString());
				for (i=0;i<XMLList(gridDesXml..row).length();i++)
				{
					rowXml=XMLList(gridDesXml..row)[i];
					//Alert.show("set:"+rowXml.field+"="+IEDIComponent(this[rowXml.componentid]).ediValue);
					row.setCell(rowXml.field,IEDIComponent(this[rowXml.componentid]).ediValue);
					//IEDIComponent(this[rowXml.field]).ediValue;
				}
				newTable.addRow(row);
				newTable.commitToServer();
				EDIAlert.show("已提交服务器");
			}
		}
		private function exitBtnClickHandler(event:MouseEvent):void
		{
			//Alert.show("exitBtnClickHandler");
			//Alert.show(""+this.parentApplication.toString());
			//Alert.show("parentDocument:"+this.parentDocument.toString());
			//Alert.show("parentDocument:"+this.parent.parent.toString());
			PopUpManager.removePopUp(IFlexDisplayObject(this.parent.parent));
		}
	}
}